<?php

namespace app\common\model;

use think\Db;
use think\Model;

class LakalaModel
{
    private $appid = 'OP00002755';
    private $mchSerialNo = '018f2879708d';
    private $mercId = '8221210552100HU';
    private $merchantPrivateKeyPath = 'lakala/api_private_key.pem';
    private $lklCertificatePath = 'lakala/api_cert.cer';
    private $lklVerifyPath = 'lakala/lkl-apigw-v1.cer';
    private $subject;
    private $schema = 'LKLAPI-SHA256withRSA';
    private $version = '3.0';
    private $outOrderNo;
    private $amount;
    private $notifyUrl;
    private $uoUrl = 'https://s2.lakala.com/api/v3/ccss/counter/order/special_create';
    private $searchUrl = 'https://s2.lakala.com/api/v3/ccss/counter/order/query';

    /**
     * 设置APPId
     */
    public function setAppid($appid)
    {
        $this->appid = $appid;
    }

    /**
     * 设置mchSerialNo
     */
    public function setMchSerialNo($mchSerialNo)
    {
        $this->mchSerialNo = $mchSerialNo;
    }

    /**
     * 设置mercId
     */
    public function setMercId($mercId)
    {
        $this->mercId = $mercId;
    }

    /**
     * 设置merchantPrivateKeyPath
     */
    public function setMerchantPrivateKeyPath($merchantPrivateKeyPath)
    {
        $this->merchantPrivateKeyPath = $merchantPrivateKeyPath;
    }

    /**
     * 设置lklCertificatePath
     */
    public function setLklCertificatePath($lklCertificatePath)
    {
        $this->lklCertificatePath = $lklCertificatePath;
    }

    /**
     * 设置out_order_no
     */
    public function setOutOrderNo($outOrderNo)
    {
        $this->outOrderNo = $outOrderNo;
    }

    /**
     * 设置subject
     */
    public function setSubject($subject)
    {
        $this->subject = $subject;
    }

    /**
     * 设置amount
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    /**
     * 设置notifyUrl
     */
    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl = $notifyUrl;
    }
    public function search($orderNo){
        $params = [
            'out_order_no'         => $orderNo,
            'merchant_no'          => $this->mercId,
        ];
        $requestData = [
            'req_data' => $params,
            'version'  => $this->version,
            'req_time' => date('YmdHis'),
        ];
        $body = json_encode($requestData, JSON_UNESCAPED_UNICODE);
        $authorization = $this->getAuthorization($body);
        $return =$this->post($this->searchUrl, $body, $authorization);
        if ($return['code']=='000000'){
            if ($return['resp_data']['order_status']==2){
                return true;
            }
        }
        return false;
    }

    public function pay($order,$pay)
    {
        $orderNo = $this->generateOrderNumber().$order['id'].rand(100,99);
        $time = strtotime('+1 days');
        $params = [
            'out_order_no'         => $orderNo,
            'merchant_no'          => $this->mercId,
            'total_amount'         => $order['main_free']*100,
            'order_efficient_time' => date('YmdHis', $time),
            'notify_url'           => 'http://'.$_SERVER['HTTP_HOST']."/index/lakala/lakalNotify/id/".$order['id'].'/type/'.$order['type'].'/channel_id/'.$pay['id'],
            'support_refund'       => 1,
            'support_repeat_pay'   => 1,
            'order_info'           => $this->subject,
            'extend_info'          => $this->subject,
            'counter_param'        => json_encode(['pay_mode' => 'WECHAT',]),
            'counter_remark'       => $order['car_num'],
        ];
        $requestData = [
            'req_data' => $params,
            'version'  => $this->version,
            'req_time' => date('YmdHis'),
        ];
        $body = json_encode($requestData, JSON_UNESCAPED_UNICODE);
        $authorization = $this->getAuthorization($body);
        $return = $this->post($this->uoUrl, $body, $authorization);
        if ($return['code'] == '000000') {

            $addData = [
                'one_id'      => $order['id'],
                'url'         => $return['resp_data']['counter_url'],
                'create_date' => time(),
                'order_no'    => $orderNo,
                'expire_time' => $time,
            ];
            Db::name('list_one_qrcode')->insertGetId($addData, true);
            return ['code' => 1, 'data' => $return['resp_data']['counter_url']];
        } else {
            return ['code' => 0, 'data' => '支付失败'];
        }
    }

    function generateOrderNumber()
    {
        $timestamp = time(); // 当前时间戳
        $random = mt_rand(1000, 9999); // 生成一个 4 位随机数
        $orderNumber = $timestamp . $random; // 拼接时间戳和随机数
        return $orderNumber;
    }

    //签名
    public function getAuthorization($body)
    {
        $nonceStr = $this->getRandom(12);
        $timestamp = time();

        $message = $this->appid . "\n" . $this->mchSerialNo . "\n" . $timestamp . "\n" . $nonceStr . "\n" . $body . "\n";
        $key = openssl_get_privatekey(file_get_contents($this->merchantPrivateKeyPath));

        openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256);
        openssl_free_key($key);

        return $this->schema . " appid=\"" . $this->appid . "\"," . "serial_no=\"" . $this->mchSerialNo . "\"," . "timestamp=\"" . $timestamp . "\"," . "nonce_str=\"" . $nonceStr . "\"," . "signature=\"" . base64_encode($signature) . "\"";
    }

    //请求
    public function post($url, $data, $authorization)
    {

        $headers = [
            "Authorization: " . $authorization,
            "Accept: application/json",
            "Content-Type:application/json",
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        return json_decode($res, true);
    }
    /**
     * 获取随机字符串
     */
    public function getRandom($len)
    {
        $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $count = strlen($base);
        $random = '';
        for ($i = 0; $i < $len; $i++) {
            $random .= $base[rand(0, $count - 1)];
        }
        return $random;
    }

}